//
//  ZXFDXuanZeZiYuanList.m
//  SanYiTeaching
//
//  Created by 李文强 on 2019/4/22.
//  Copyright © 2019 SanYi. All rights reserved.
//

#import "ZXFDXuanZeZiYuanList.h"
#import "SYRequestAPI+TongYong.h"
#import "SYRequestAPI+FuDao.h"


@implementation ZXFDXuanZeZiYuanList

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame andID:(NSString *)fdID{
    if ([super initWithFrame:frame]) {
        [self initSubView];
        [self layout];
        self.fdID = fdID;
        [self getZiYuanLisetRequest];
    }
    return self;
}
//- (instancetype)initWithFrame:(CGRect)frame{
//
//}
- (void)initSubView{
    _idArray = [NSMutableArray new];
    self.resourceArray = [NSMutableArray new];
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.tableView];
    _tableView.frame = CGRectMake(20, 44, self.frame.size.width-40, self.frame.size.height-44);
    [_tableView registerClass:[ZXFDXuanZeZiYuanCellTableViewCell class] forCellReuseIdentifier:@"ZXFDXuanZeZiYuanCellTableViewCell"];
    _tableView.delegate = self;
    _tableView.dataSource  =self;
    
    [self addSubview:self.navView];
    [self.tableView headerRefreshBlock:^{
        [self getZiYuanLisetRequest];
    }];
  
}
- (void)layout{
    [_navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.top.equalTo(@0);
        make.height.equalTo(@44);
    }];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.right.equalTo(@0).offset(-20);
        make.top.equalTo(@44);
        make.bottom.equalTo(@0);
    }];
}
- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, APP_HEIGHT-84) style:UITableViewStylePlain];
        tableView.delegate  =self;
        tableView.dataSource = self;
        tableView.backgroundColor = CONTENTBACKCOLOR;
        [tableView registerClass:[ZXFDXuanZeZiYuanCellTableViewCell class] forCellReuseIdentifier:@"ZXFDXuanZeZiYuanCellTableViewCell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}
- (ZXFDCCVNav *)navView{
    if (!_navView) {
        ZXFDCCVNav *view = [[ZXFDCCVNav alloc]init];
        view.backgroundColor = CONTENTBACKCOLOR;
        view.delegate = self;
        view.titleLabe.text = @"创建班级-添加资源";
        [view addSubview:self.complateBtn];
        [_complateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@0).offset(-10);
            make.centerY.equalTo(view.mas_centerY);
            make.width.equalTo(@100);
            make.height.equalTo(@30);
        }];
        _navView = view;
    }
    return _navView;
}
- (void)backClick{
    [UIView animateWithDuration:0.5 animations:^{
        self.frame = CGRectMake(self.frame.size.width,0, self.frame.size.width, self.frame.size.height);
    }completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
   return _resourceArray.count+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else{
        ResourceMainModel *model = _resourceArray[section-1];
        return model.dataFileArray.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 100;
    }else{
       return 50;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return self.topView;
    }else{
        _cellHeader = [[ZXFDXuanZeXueShengFileHeaderView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50)];
//        if (section%2 == 1) {
            _cellHeader.backView.backgroundColor = [UIColor whiteColor];
//        }else{
//            _cellHeader.backView.backgroundColor = [UIColorChange colorwithHexString:@"#F8F8F8"];
//        }
        ResourceMainModel *model = _resourceArray[section-1];
        _cellHeader.titleLabel.text = model.courseName;
        _cellHeader.detailLabel.text = [NSString stringWithFormat:@"文件%@  大小%@",model.files,model.size];
        NSMutableArray * array = [NSMutableArray new];
        for (int i = 0; i<model.dataFileArray.count; i++) {
            MyZiYuanLieBiaoModel *mod = model.dataFileArray[i];
            [array addObject:mod.ZYid];
        }
        if (arrayEquel(array,_idArray)) {
            _cellHeader.selectedButton.selected = YES;
        }else{
            _cellHeader.selectedButton.selected = NO;
        }
        
        __weak typeof(self)weakeSelf = self;
        _cellHeader.selectedAllBlock = ^{
            ResourceMainModel *model = weakeSelf.resourceArray[section-1];
            [weakeSelf.idArray removeAllObjects];
            for (int i = 0; i<model.dataFileArray.count; i++) {
                MyZiYuanLieBiaoModel *mod = model.dataFileArray[i];
                [weakeSelf.idArray addObject:mod.ZYid];
            }
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:section];
            [weakeSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        _cellHeader.noSelectedAllBlock = ^{
            ResourceMainModel *model = weakeSelf.resourceArray[section-1];
            for (int i = 0; i<model.dataFileArray.count; i++) {
                MyZiYuanLieBiaoModel *mod = model.dataFileArray[i];
                if ([weakeSelf.idArray containsObject:mod.ZYid]) {
                     [weakeSelf.idArray removeObject:mod.ZYid];
                }
            }
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:section];
            [weakeSelf.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        };
        return _cellHeader;
    }
    
}
- (ZXFDXuanZeZiYuanTopView *)topView{
    if (!_topView) {
        ZXFDXuanZeZiYuanTopView *view = [[ZXFDXuanZeZiYuanTopView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 100)];
        view.topShowView.selectedAllBlock = ^{
            [self->_idArray removeAllObjects];
            for (ResourceMainModel *model in self->_resourceArray) {
                for (int i = 0; i<model.dataFileArray.count; i++) {
                    MyZiYuanLieBiaoModel *mod = model.dataFileArray[i];
                    [self->_idArray addObject:mod.ZYid];
                }
            }
            [self->_tableView reloadData];
        };
        view.startTimeLabel.hidden = YES;
        view.startTime.hidden = YES;
        view.endTimeLabel.hidden = YES;
        view.endTime.hidden = YES;
        view.startLineView.hidden = YES;
        view.endLineView.hidden = YES;
        view.topShowView.noSelectedAllBlock = ^{
            [self->_idArray removeAllObjects];
            [self->_tableView reloadData];
        };
        _topView = view;
    }
    return _topView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZXFDXuanZeZiYuanCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZXFDXuanZeZiYuanCellTableViewCell" forIndexPath:indexPath];
    
    if (!cell) {
        cell = [[ZXFDXuanZeZiYuanCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ZXFDXuanZeZiYuanCellTableViewCell"];
    }
    cell.backgroundColor = CONTENTBACKCOLOR;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ResourceMainModel *fm = _resourceArray[indexPath.section-1];
    MyZiYuanLieBiaoModel *mod = fm.dataFileArray[indexPath.row];
    [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:mod.icon] placeholderImage:[UIImage imageNamed:@"zy_collection_xjwjj.png"]];
    cell.titleLabel.text = mod.name;
    cell.sizeLabel.text = mod.size;
    cell.titleLabel.text = mod.duration;
    cell.zyID = mod.ZYid;
    cell.selcetedBlock = ^(NSString* zyID) {
        if ([self->_idArray containsObject:zyID]) {
            return ;
        }
        [self->_idArray addObject:zyID];
    };
    cell.noSelcetedBlock = ^(NSString* zyID) {
        [self->_idArray removeObject:zyID];
    };
    if ([_idArray containsObject:mod.ZYid]) {
        cell.selectedButton.selected = YES;
    }else{
        cell.selectedButton.selected = NO;
    }
    return cell;
}
- (UIView *)backV{
    UIView *back = [[UIView alloc]init];
    back.backgroundColor = SELECTEDCOLOR;
    return back;
}
- (UIButton *)complateBtn{
    if (!_complateBtn) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"下一步" forState:UIControlStateNormal];
        [btn setTitleColor:SELECTEDCOLOR forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn addTarget:self action:@selector(complateClicl:) forControlEvents:UIControlEventTouchUpInside];
        _complateBtn = btn;
    }
    return _complateBtn;
}
- (void)complateClicl:(UIButton *)sender{
    if (self->_resourceArray.count == 0) {
        [XSInfoView showInfo:@"暂无资源" onView:[UIApplication sharedApplication].keyWindow.rootViewController];
        [NSObject executeRunloop:^{
            self.xueShengView.fdID = self.fdID;
            [self addSubview:self.xueShengView];
            [self->_xueShengView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.top.equalTo(@0);
                make.right.equalTo(@0);
                make.bottom.equalTo(@0);
            }];
        } afterDelay:2];
        return;
    }
    [self addResourceRequest];
}
- (ZaiXianFuDaoTianJiaXueShengView *)xueShengView{
    if (!_xueShengView) {
        ZaiXianFuDaoTianJiaXueShengView *view = [[ZaiXianFuDaoTianJiaXueShengView alloc]init];
        _xueShengView = view;
    }
    return _xueShengView;
}
#pragma mark - 请求资源列表
- (void)getZiYuanLisetRequest{
    NSDictionary *parama = @{@"subjectId":@"0",
                             @"courseId":@"0",
                             @"lessonIds":@"",
                             @"classId":self.fdID
    };
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI sy_getCommonServiceLessonResource:parama success:^(id  _Nonnull responseObject) {
      //  NSLog(@"请求资源列表 %@",responseObject);
        NSArray *data = [responseObject objectForKey:@"data"];
        for (NSDictionary *dic in data) {
            ResourceMainModel *model =[ResourceMainModel yy_modelWithJSON:dic];
           
            model.dataFileArray = [NSMutableArray new];
            NSArray *array = [dic objectForKey:@"dataFiles"];
            for (NSDictionary *dic in array) {
                MyZiYuanLieBiaoModel*m = [MyZiYuanLieBiaoModel yy_modelWithJSON:dic];
            }
             [self->_resourceArray addObject:model];
        }
        [self.tableView reloadData];
        [MBProgressHUD mj_hideHUDForView:self];
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD mj_hideHUDForView:self];
    }];
}
#pragma mark - 添加资源
- (void)addResourceRequest{
    NSString *ids = [NSString new];
    for (NSString * object in _idArray) {
        if (ids.length == 0) {
            ids = [NSString stringWithFormat:@"%@",object];
        }else{
            ids = [NSString stringWithFormat:@"%@,%@",ids,object];
        }
    }
    NSDictionary *parama = @{@"lessonIds":ids,//必填,添加传0，否则传ID
                             @"id":self.fdID};
    [MBProgressHUD mj_hideHUDForView:self];
   // NSLog(@"得到的资源参数 %@",parama);
    [MBProgressHUD mj_showMessage:nil toView:self];
    [SYRequestAPI fd_TutorTutorClassServiceClassAdd:parama success:^(id responseObject) {
      //  NSLog(@"添加资源  %@",responseObject);
        [self addSubview:self.xueShengView];
        self.xueShengView.fdID = self.fdID;
        [self->_xueShengView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.top.equalTo(@0);
            make.right.equalTo(@0);
            make.bottom.equalTo(@0);
        }];
        
    } fail:^(NSError *error) {
        [MBProgressHUD mj_hideHUDForView:self];
        [XSInfoView showInfo:error.domain onView:[UIApplication sharedApplication].keyWindow.rootViewController];
    }];

}

BOOL arrayEquel(NSArray *array1,NSArray *array2) {
    if (array1.count != array2.count) {
        return NO;
    }
    for (NSString *str in array1) {
        if (![array2 containsObject:str]) {
            return NO;
        }
    }
    return YES;
}
@end
